<template>
  <tn-navbar  back-icon="" :bottom-shadow="false" fixed>
    <text class="title">挪个车嘛</text>
  </tn-navbar>
  <view class="container">
    <!-- 车辆信息不存在或已停用的展示 -->
    <template v-if="!carExists">
      <view class="error-state">
        <view class="error-icon">
          <view class="car-icon">
            <view class="car-body">
              <view class="car-top"></view>
              <view class="car-bottom">
                <view class="wheel"></view>
                <view class="wheel"></view>
              </view>
            </view>
            <view class="error-badge">!</view>
          </view>
        </view>
        <text class="error-title">抱歉，该挪车码暂无法使用</text>
        <text class="error-desc">该挪车码可能已被停用或不存在</text>
      </view>
    </template>

    <!-- 正常的车辆信息展示 -->
    <template v-else>
      <!-- 车辆信息卡片 -->
      <view class="car-info-card">
        <text class="license-plate">{{ carInfo.licensePlate }}</text>
        <view class="owner-message" v-if="carInfo.message">
          <text class="message-label">车主留言：</text>
          <text class="message-content">{{ carInfo.message }}</text>
        </view>
      </view>

      <!-- 发送前的表单内容 -->
      <template v-if="!isWaiting">
        <!-- 紧急程度选择 -->
        <view class="urgency-section">
          <text class="section-title">请选择紧急程度</text>
          <view class="urgency-options">
            <view
                v-for="(option, index) in urgencyOptions"
                :key="index"
                class="urgency-option"
                :class="{ 'selected': selectedUrgency === index }"
                @tap="selectUrgency(index)"
            >
              <view class="urgency-icon">
                <tn-icon
                    :name="option.icon"
                    :size="56"
                    :color="selectedUrgency === index ? '#ffffff' : option.color"
                ></tn-icon>
              </view>
              <text class="urgency-text">{{ option.text }}</text>
              <text class="urgency-desc">{{ option.description }}</text>
            </view>
          </view>
        </view>

        <!-- 备注信息 -->
        <view class="remark-section">
          <text class="section-title">备注信息（选填）</text>
          <textarea
              class="remark-input"
              placeholder="请简要描述您的挪车需求，如：您的车挡住了出口"
              v-model="remark"
              maxlength="100"
          ></textarea>
          <text class="word-count">{{ remark.length }}/100</text>
        </view>

        <!-- 快捷回复选项 -->
        <view class="quick-reply-section">
          <view class="quick-reply-tags">
            <text
                v-for="(tag, index) in quickReplyTags"
                :key="index"
                class="quick-reply-tag"
                :class="{ 'selected': selectedTags.includes(tag) }"
                @tap="toggleTag(tag)"
            >{{ tag }}
            </text>
          </view>
        </view>
        <!-- 备注信息 -->
        <view class="remark-section" v-if="carInfo.msg_log.length > 0">
          <text class="section-title">挪车日志</text>
          <!-- 修改消息记录区域 -->
          <view class="message-log-section" >
            <scroll-view
                class="message-log-list"
                scroll-y
                :scroll-into-view="'msg-' + carInfo.msg_log.length"
            >
              <view
                  v-for="(msg, index) in carInfo.msg_log"
                  :key="msg.id"
                  :id="'msg-' + (index + 1)"
                  class="message-log-item"
                  :class="{'system-message': msg.type === 0}"
              >
                <view class="message-time">{{ msg.itime }}</view>
                <view class="message-content">{{carInfo.user_id == msg.user_id && msg.type==1?'车主:':'我:'}}{{ msg.content }}</view>
              </view>
            </scroll-view>
          </view>
        </view>
      </template>

      <!-- 等待动画 -->
      <view v-else class="waiting-animation-container">
        <view class="road-background">
          <view class="car-animation">
            <view class="car-body">
              <view class="car-top"></view>
              <view class="car-bottom">
                <view class="wheel wheel-left"></view>
                <view class="wheel wheel-right"></view>
              </view>
            </view>
          </view>
          <view class="road-line"></view>
        </view>
        <view class="waiting-info">
          <view class="countdown-circle">
            <view class="countdown-circle-inner" :style="{ transform: `scale(${countdownProgress})` }"></view>
            <text class="countdown-text" v-if="carInfo.move_car_record_status !=4">{{ formattedCountdown }}</text>
          </view>
          <text class="waiting-text" v-if="carInfo.move_car_record_status !=4">{{ waitingText }}</text>
          <text class="waiting-tip">{{
              carInfo.move_car_record_status != 4 || carInfo.request_qty ? waitingTip : '请用其他方式联系车主'
            }}
          </text>
        </view>

        <!-- 添加车主回复显示区域 -->
        <view v-if="ownerReply.message || carInfo.move_car_record_status >=2" class="owner-response">
          <view class="response-header">
            <text class="response-title">车主回复</text>
            <text class="response-time">{{ ownerReply.time }}</text>
          </view>
          <view class="response-content">
            <text class="response-message">{{ ownerReply.message }}</text>
          </view>
        </view>

        <!-- 修改消息记录区域 -->
        <view class="message-log-section">
          <scroll-view
              class="message-log-list"
              scroll-y
              :scroll-into-view="'msg-' + carInfo.msg_log.length"
          >
            <view
                v-for="(msg, index) in carInfo.msg_log"
                :key="msg.id"
                :id="'msg-' + (index + 1)"
                class="message-log-item"
                :class="{'system-message': msg.type === 0}"
            >
              <view class="message-time">{{ msg.itime }}</view>
              <view class="message-content">{{carInfo.user_id == msg.user_id && msg.type==1?'车主:':'我:'}}{{ msg.content }}</view>
            </view>
          </scroll-view>
        </view>
      </view>
    </template>

    <!-- 底部按钮区域 -->
    <view class="bottom-actions">
      <template v-if="carExists && !isWaiting">
        <button
            class="primary-btn"
            :disabled="!canSubmit"
            @tap="sendRequest"
        >发送挪车请求
        </button>
        <button
            class="secondary-btn"
            @tap="showEmergencyContacts"
        >查看其他联系方式
        </button>
      </template>
      <button
          v-else
          class="secondary-btn"
          @tap="showEmergencyContacts"
      >查看其他联系方式
      </button>
    </view>

    <!-- 温馨提示 -->
    <view class="tips-section safe-bottom" v-if="carExists">
      <text class="tips-title">温馨提示：</text>
      <text class="tips-content">1. 请合理选择紧急程度，避免造成不必要的打扰</text>
      <text class="tips-content">2. 系统会记录您的请求信息，恶意骚扰将被列入黑名单</text>
      <text class="tips-content">3. 如遇紧急情况，建议选择其他解决方案</text>
    </view>

    <!-- 车主回复弹窗 -->
    <view class="owner-reply-popup" v-if="showOwnerReply">
      <view class="reply-content">
        <view class="reply-header">
          <text class="reply-title">车主回复</text>
          <text class="close-btn" @tap="closeReply">×</text>
        </view>
        <view class="reply-body">
          <text class="reply-message">{{ ownerReply.message }}</text>
          <text class="reply-time">{{ ownerReply.time }}</text>
        </view>
        <view class="reply-footer">
          <button class="confirm-btn" @tap="closeReply">知道了</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted} from 'vue';
import TnIcon from '@/uni_modules/tuniaoui-vue3/components/icon/src/icon.vue'
import {getDetailsByKey, sendMoveRequest, subMessageTemplateList, wxLogin} from "@/common/api";
import URL_CONGFIG from '@/utils/config';
import {onShow} from '@dcloudio/uni-app';

// 添加模拟数据
const mockData = {
  // 模拟数据1：正常状态的车辆信息
  normal: {
    code: 200,
    msg: "success",
    data: {
      id: 10,
      user_id: 12,
      message: "请联系物业",
      status: true,
      licensePlate: "苏Y665557",
      notification: null,
      move_car_record: null,
      msg_log: [],
      request_qty: false,
      move_car_record_status: null,
      other_contact_info: "如果车主未及时回应，您可以拨打如下电话号码：114、12580、12123、110以及112。拨打114后，按7号键即可转接至挪车服务，告知客服人员所需挪动的车牌号，他们会帮助您联系到车主。拨打12580并转8键进行登记，提供您的车牌号，系统便会查询并获取车辆所有人联系方式，通知其挪车。使用12123app的一键挪车功能，后台将自动查询车主信息并发出挪车通知。",
      interval_time: "300",
      waiting_time: 0
    },
    timestamp: 1742880699
  },
  
  // 模拟数据2：车辆信息不存在或已停用
  invalid: {
    code: 200,
    msg: "success",
    data: {
      id: null,
      user_id: null,
      message: null,
      status: false,
      licensePlate: "",
      notification: null,
      move_car_record: null,
      msg_log: [],
      request_qty: false,
      move_car_record_status: null,
      other_contact_info: "如果车主未及时回应，您可以拨打如下电话号码：114、12580、12123、110以及112。",
      interval_time: "300",
      waiting_time: 0
    },
    timestamp: 1742880699
  },
  
  // 模拟数据3：等待车主回应状态
  waiting: {
    code: 200,
    msg: "success",
    data: {
      id: 10,
      user_id: 12,
      message: "请联系物业",
      status: true,
      licensePlate: "苏Y665557",
      notification: null,
      move_car_record: null,
      msg_log: [],
      request_qty: true,
      move_car_record_status: 1, // 1表示等待中
      other_contact_info: "如果车主未及时回应，您可以拨打如下电话号码：114、12580、12123、110以及112。",
      interval_time: "300",
      waiting_time: 240 // 剩余等待时间
    },
    timestamp: 1742880699
  },
  
  // 模拟数据4：车主已回复状态
  replied: {
    code: 200,
    msg: "success",
    data: {
      id: 10,
      user_id: 12,
      message: "请联系物业",
      status: true,
      licensePlate: "苏Y665557",
      notification: null,
      move_car_record: null,
      msg_log: [
        {
          id: 1,
          user_id: 12, // 车主ID
          type: 1, // 1表示用户消息
          content: "我马上过来挪车，请稍等5分钟",
          itime: "2023-11-22 14:30:25"
        },
        {
          id: 2,
          user_id: 15, // 请求者ID
          type: 1,
          content: "好的，谢谢",
          itime: "2023-11-22 14:31:05"
        }
      ],
      request_qty: true,
      move_car_record_status: 2, // 2表示已回复
      other_contact_info: "如果车主未及时回应，您可以拨打如下电话号码：114、12580、12123、110以及112。",
      interval_time: "300",
      waiting_time: 180
    },
    timestamp: 1742880699
  },
  
  // 模拟数据5：请求超时状态
  timeout: {
    code: 200,
    msg: "success",
    data: {
      id: 10,
      user_id: 12,
      message: "请联系物业",
      status: true,
      licensePlate: "苏Y665557",
      notification: null,
      move_car_record: null,
      msg_log: [],
      request_qty: true,
      move_car_record_status: 4, // 4表示超时
      other_contact_info: "如果车主未及时回应，您可以拨打如下电话号码：114、12580、12123、110以及112。",
      interval_time: "300",
      waiting_time: 0
    },
    timestamp: 1742880699
  }
};

// 添加模拟模式开关
const useMockData = ref(true); // 设置为true启用模拟数据
const mockDataType = ref('normal'); // 默认使用normal模拟数据

// 车辆信息
const carInfo = ref({
  licensePlate: '',
  message: '',
  msg_log:[],
  move_car_record:{
    qrcode_user_id:0
  }
});

// 添加车辆是否存在的状态
const carExists = ref(true);

// 紧急程度选项
const urgencyOptions = [
  {
    icon: 'time',
    text: '普通',
    description: '不急，希望车主看到后尽快处理',
    color: '#3467C2'
  },
  {
    icon: 'warning',
    text: '紧急',
    description: '较急，影响到其他车辆通行',
    color: '#fa8c16'
  },
  {
    icon: 'warning-fill',
    text: '非常紧急',
    description: '非常紧急，已影响消防通道等',
    color: '#ff4d4f'
  }
];

const selectedUrgency = ref(0);
const contactPhone = ref('');
const remark = ref('');

// 快捷回复标签
const quickReplyTags = [
  '挡住出口',
  '影响通行',
  '需要外出',
  '占用车位',
  '维修需要',
  '其他原因'
];

const selectedTags = ref([]);
const key = ref("");

// 选择紧急程度
const selectUrgency = (index) => {
  selectedUrgency.value = index;
};

// 切换标签
const toggleTag = (tag) => {
  const index = selectedTags.value.indexOf(tag);
  if (index === -1) {
    selectedTags.value.push(tag);
  } else {
    selectedTags.value.splice(index, 1);
  }

  // 将选中的标签添加到备注中
  remark.value = selectedTags.value.join('，');
};

// 是否可提交
const canSubmit = computed(() => {
  return selectedUrgency.value !== -1;
});

// 等待状态相关
const isWaiting = ref(false);
const countdownSeconds = ref(60);
const countdownProgress = ref(1);
let countdownTimer = null;

// 等待状态文本
const waitingText = ref('正在等待车主回应...');
const waitingTip = ref('车主将收到您的挪车请求通知');

// 车主回复相关
const showOwnerReply = ref(false);
const ownerReply = ref({
  message: '',
  time: ''
});

// 关闭回复弹窗
const closeReply = () => {
  showOwnerReply.value = false;
};

// WebSocket相关变量
const heartbeatTimer = ref(null);
const reconnectTimer = ref(null);
const reconnectAttempts = ref(0);
const MAX_RECONNECT_ATTEMPTS = 20;
const HEARTBEAT_INTERVAL = 30000; // 30秒发送一次心跳
const RECONNECT_INTERVAL = 3000; // 3秒重连一次

// WebSocket连接函数
const connectWebSocket = () => {
  try {
    // 先关闭可能存在的连接
    uni.closeSocket({
      success: () => {
        console.log('关闭之前的连接');
      },
      complete: () => {
      }
    });

    // 创建新连接
    uni.connectSocket({
      url: `${URL_CONGFIG.WS_URL}?authorization=` + uni.getStorageSync('TOKEN'),
      success: () => {
        console.log('WebSocket连接创建成功');
      },
      fail: (error) => {
        console.error('WebSocket连接创建失败:', error);
        attemptReconnect();
      }
    });

    // 监听WebSocket连接打开
    uni.onSocketOpen(() => {
      console.log('WebSocket连接已打开');
      reconnectAttempts.value = 0;

      // 发送用户认证消息
      uni.sendSocketMessage({
        data: JSON.stringify({
          action: "userAuth",
          authorization: uni.getStorageSync('TOKEN')
        }),
        success: () => {
          console.log('认证消息发送成功');
          startHeartbeat(); // 认证后开始心跳
        },
        fail: (error) => {
          console.error('认证消息发送失败:', error);
          attemptReconnect();
        }
      });
    });

    // 监听WebSocket接收到服务器的消息
    uni.onSocketMessage((res) => {
      try {
        const data = JSON.parse(res.data);
        console.log('收到WebSocket消息:', data); // 打印完整消息以便调试

        // 检查数据结构
        if (!data) {
          console.error('收到空消息');
          return;
        }

        // 处理不同类型的消息
        switch (data.event) { // 直接使用顶层的event
          case 'pong':
            // 心跳响应，不需要处理
            break;

          case 5:
          case 6:
          case 7:
            // 添加新消息到记录
            if (data.data.data) { // 直接使用data字段
              // 确保msg_log是数组
              if (!Array.isArray(carInfo.value.msg_log)) {
                carInfo.value.msg_log = [];
              }
              // 将新消息添加到数组中
              if (Array.isArray(data.data.data)) {
                // 如果是数组，合并数组
                carInfo.value.msg_log = [...carInfo.value.msg_log, ...data.data.data];
              } else {
                // 如果是单条消息，添加到数组末尾
                carInfo.value.msg_log.push(data.data.data);
              }
            }
            if (data.data.status !== undefined) {
              carInfo.value.move_car_record_status = data.data.status;
              isWaiting.value = true;
            }
            if(data.event == 5){
              // 处理车主回复
              handleOwnerReply(data);
              break;
            }
            break;
          default:
            console.log('收到未知类型消息:', data);
        }
      } catch (error) {
        console.error('解析消息失败:', error, '原始消息:', res.data);
      }
    });

    // 监听WebSocket错误
    uni.onSocketError((res) => {
      console.error('WebSocket错误:', res);
      attemptReconnect();
    });

    // 监听WebSocket关闭
    uni.onSocketClose(() => {
      console.log('WebSocket已关闭');
      stopHeartbeat();
      attemptReconnect();
    });

  } catch (error) {
    console.error('WebSocket连接失败:', error);
    attemptReconnect();
  }
};
// 页面显示时刷新数据
onShow(async () => {
  getVehicleInfo(key.value);
  startRequestProcess(); // 开始请求流程

});
// 显示其他联系方式
const showEmergencyContacts = () => {
  uni.showModal({
    title: '其他联系方式',
    content: carInfo.value.other_contact_info,
    showCancel: false
  });
};
// 发送心跳
const sendHeartbeat = () => {
  uni.sendSocketMessage({
    data: JSON.stringify({type: 'ping'}),
    success: () => {
      console.log('心跳发送成功');
    },
    fail: (error) => {
      console.error('发送心跳失败:', error);
      attemptReconnect();
    }
  });
};

// 开始心跳检测
const startHeartbeat = () => {
  stopHeartbeat(); // 先清除可能存在的心跳定时器
  heartbeatTimer.value = setInterval(sendHeartbeat, HEARTBEAT_INTERVAL);
};

// 停止心跳检测
const stopHeartbeat = () => {
  if (heartbeatTimer.value) {
    clearInterval(heartbeatTimer.value);
    heartbeatTimer.value = null;
  }
};

// 尝试重新连接
const attemptReconnect = () => {
  if (reconnectAttempts.value >= MAX_RECONNECT_ATTEMPTS) {
    console.log('达到最大重连次数，停止重连');
    return;
  }

  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value);
  }

  reconnectTimer.value = setTimeout(() => {
    console.log(`第${reconnectAttempts.value + 1}次尝试重连...`);
    reconnectAttempts.value++;
    connectWebSocket();
  }, RECONNECT_INTERVAL);
};

// 清理资源
onUnmounted(() => {
  uni.closeSocket({
    success: () => {
      console.log('WebSocket已关闭');
    },
    complete: () => {
    }
  });
  stopHeartbeat();
  if (reconnectTimer.value) {
    clearTimeout(reconnectTimer.value);
  }
  // 移除所有事件监听
  uni.offSocketOpen();
  uni.offSocketMessage();
  uni.offSocketError();
  uni.offSocketClose();
});

// 修改原有的connectWebSocket调用
const startRequestProcess = async () => {
  // 添加等待
  connectWebSocket(); // 建立WebSocket连接
};


// 修改sendRequest函数，成功后调用startRequestProcess
const sendRequest = async () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '请选择紧急程度',
      icon: 'none'
    });
    return;
  }

  try {
    // 获取订阅消息模板列表
    const templates =  uni.getStorageSync('subMessageTemplateList');
    if (templates) {
      // 调用小程序订阅消息接口
      const result = await uni.requestSubscribeMessage({
        tmplIds: templates
      });
      // 根据订阅结果处理
      if (result.errMsg === 'requestSubscribeMessage:ok') {
        // 检查每个模板的订阅状态
        console.log(result, 'resultresult')
        const hasRejected = Object.values(result).includes('reject');
        if (hasRejected) {

        }
      }
    }
  } catch (error) {
    console.error('订阅消息失败:', error);
  }
  uni.showLoading({
    title: '发送中...'
  });

  try {
    const requestData = {
      urgencyLevel: selectedUrgency.value,
      remark: remark.value,
      key: key.value
    };

    // 使用模拟数据或真实API
    if (useMockData.value) {
      // 模拟发送成功，切换到等待状态
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: '发送成功',
          icon: 'success'
        });
        mockDataType.value = 'waiting'; // 切换到等待状态
        getVehicleInfo(key.value);
        startCountdown();
      }, 1000);
    } else {
      await sendMoveRequest(requestData);
      uni.hideLoading();
      uni.showToast({
        title: '发送成功',
        icon: 'success'
      });
      startCountdown();
    }
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || '发送失败，请重试',
      icon: 'none'
    });
  }
};

// 获取车辆信息
onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;

  if (options.scene) {
    // 实际项目中应调用API获取车辆信息
    key.value = options.scene
    // if(!uni.getStorageSync('TOKEN') || uni.getStorageSync('TOKEN')==null || uni.getStorageSync('TOKEN')==''){
    //   let { code }  = await getLoginWeixinCode();
    //   _wxLogin(code);
    // }else {
    //
    // }
    getVehicleInfo(key.value);
  }
});
const _wxLogin = async(code) =>{
  try {
    let data = await wxLogin({code});
    uni.hideLoading();
    uni.setStorageSync('TOKEN',data.token);
    getVehicleInfo(key.value);
  } catch(err){

  }
}
// 获取车辆信息
const getVehicleInfo = async (key) => {
  // 添加等待
  if(key=='' || key==null){
    return false;
  }
  await uni.$appLogin;

  try {
    let data;
    
    // 使用模拟数据或真实API
    if (useMockData.value) {
      data = mockData[mockDataType.value].data;
      console.log('使用模拟数据:', mockDataType.value);
      
      // 添加模拟数据切换按钮（仅在开发环境）
      setTimeout(() => {
        if (process.env.NODE_ENV === 'development') {
          uni.showActionSheet({
            itemList: ['正常状态', '无效车辆', '等待回应', '已回复', '请求超时'],
            success: function (res) {
              const types = ['normal', 'invalid', 'waiting', 'replied', 'timeout'];
              mockDataType.value = types[res.tapIndex];
              getVehicleInfo(key);
            }
          });
        }
      }, 500);
    } else {
      const response = await getDetailsByKey({key: key});
      data = response;
    }
    
    carInfo.value = data;
    if (carInfo.value.move_car_record_status == 4) {
      isWaiting.value = true;
    }

    // 确保msg_log是数组
    if (!Array.isArray(carInfo.value.msg_log)) {
      carInfo.value.msg_log = [];
    }

    // 如果消息记录不为空，获取最后一条车主发送的消息
    if (carInfo.value.msg_log.length > 0) {
      // 倒序遍历查找最后一条车主发送的消息
      for (let i = carInfo.value.msg_log.length - 1; i >= 0; i--) {
        const msg = carInfo.value.msg_log[i];
        if (carInfo.value.user_id == msg.user_id && msg.type == 1) {
          // 找到车主发送的消息，设置到 ownerReply
          ownerReply.value = {
            message: msg.content,
            time: msg.itime
          };
          break; // 找到后跳出循环
        }
      }
    }

    if (!data.status) {
      carExists.value = false;
      return;
    }
    if (carInfo.value.move_car_record_status == 2 && carInfo.value.waiting_time >0) {
      // 更新等待状态文本
      waitingText.value = '车主已回复';
      waitingTip.value = '5分钟后可再次发送请求';
      isWaiting.value = true;
      // 重新开始5分钟倒计时
      startWaitingCountdown(carInfo.value.waiting_time);
    }
    if ( carInfo.value.waiting_time >0) {
      // 更新等待状态文本
      waitingText.value = '正在等待车主回应...';
      waitingTip.value = '5分钟后可再次发送请求';
      isWaiting.value = true;
      // 重新开始5分钟倒计时
      startWaitingCountdown(carInfo.value.waiting_time);
    }
    if (carInfo.value.request_qty && carInfo.value.move_car_record_status == 2) {
      // 更新等待状态文本
      waitingTip.value = '车主已回复，请等待车主处理';
      isWaiting.value = true;
      carInfo.value.move_car_record_status = 4
      // 重新开始5分钟倒计时
      // startWaitingCountdown(carInfo.value.waiting_time);
    }
    carExists.value = true;
    selectedUrgency.value = 0;

  } catch (error) {
    console.error('获取车辆信息失败:', error);
    carExists.value = false;
  }
};

// 开始倒计时（初始1分钟）
const startCountdown = () => {
  // 清除之前的定时器
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  isWaiting.value = true;
  countdownSeconds.value = carInfo.value.interval_time;
  countdownProgress.value = 1;

  countdownTimer = setInterval(() => {
    countdownSeconds.value--;
    countdownProgress.value = countdownSeconds.value / 60;

    if (countdownSeconds.value <= 0) {
      clearInterval(countdownTimer);
      isWaiting.value = false;
      uni.showToast({
        title: '车主暂未回应，可以再次发送请求',
        icon: 'none',
        duration: 2000
      });
    }
  }, 1000);
};



// 处理车主回复
const handleOwnerReply = (data) => {
  ownerReply.value = {
    message: data.data.data.content,
    time:data.data.data.itime
  };
  // 更新等待状态文本
  waitingText.value = '车主已回复';
  waitingTip.value = '请耐心等待';
  // 显示回复弹窗
  showOwnerReply.value = true;
  // 震动提示
  uni.vibrateShort();
  // 重新开始5分钟倒计时
  // startWaitingCountdown(time);
};

// 5分钟等待倒计时
const startWaitingCountdown = (time=300) => {
  // 清除之前的定时器，避免重复计时
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  countdownSeconds.value = time; // 5分钟 = 300秒
  countdownProgress.value = 1;

  countdownTimer = setInterval(() => {
    countdownSeconds.value--;
    countdownProgress.value = countdownSeconds.value / 300; // 使用300作为基数

    if (countdownSeconds.value <= 0) {
      clearInterval(countdownTimer);
      isWaiting.value = false;
      uni.showToast({
        title: '可以再次发送挪车请求',
        icon: 'none',
        duration: 2000
      });
    }
  }, 1000);
};

// 格式化倒计时显示
const formattedCountdown = computed(() => {
  const minutes = Math.floor(countdownSeconds.value / 60);
  const seconds = countdownSeconds.value % 60;
  return `${minutes}:${seconds.toString().padStart(2, '0')}`;
});
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  min-height: 80vh;
  background-color: #f8f8f8;
}

.car-info-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.license-plate {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  display: block;
  text-align: center;
  margin-bottom: 20rpx;
}

.owner-message {
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
}

.message-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 10rpx;
}

.message-content {
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
}

.urgency-section,
.contact-section,
.remark-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.urgency-options {
  display: flex;
  justify-content: space-between;
  margin-top: 20rpx;
  gap: 20rpx;
}

.urgency-option {
  flex: 1;
  padding: 24rpx 16rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s ease;

  &.selected {
    background-color: var(--color);
    transform: translateY(-2rpx);
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

    .urgency-text, .urgency-desc {
      color: #ffffff;
    }
  }

  &:nth-child(1) {
    --color: #3467C2;
  }

  &:nth-child(2) {
    --color: #fa8c16;
  }

  &:nth-child(3) {
    --color: #ff4d4f;
  }
}

.urgency-icon {
  width: 96rpx;
  height: 96rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16rpx;
}

.urgency-text {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 8rpx;
  font-weight: bold;
}

.urgency-desc {
  font-size: 24rpx;
  color: #666;
  text-align: center;
  line-height: 1.4;
}

.contact-input {
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
}

.remark-input {
  width: 100%;
  height: 160rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}

.word-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
}

.quick-reply-section {
  margin-bottom: 30rpx;
}

.quick-reply-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.quick-reply-tag {
  padding: 12rpx 24rpx;
  background-color: #f0f0f0;
  border-radius: 100rpx;
  font-size: 26rpx;
  color: #666;
  transition: all 0.3s;
}

.quick-reply-tag.selected {
  background-color: #e8f5e9;
  color: #1aad19;
}

.bottom-actions {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 30rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
  box-sizing: border-box;
}

.waiting-animation-container {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin: 30rpx 0;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.road-background {
  width: 100%;
  height: 200rpx;
  position: relative;
  overflow: hidden;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
}

.road-line {
  position: absolute;
  top: 50%;
  left: 0;
  width: 100%;
  height: 4rpx;
  background: repeating-linear-gradient(
          90deg,
          #ddd,
          #ddd 20rpx,
          transparent 20rpx,
          transparent 40rpx
  );
  animation: moveRoad 1s linear infinite;
}

.car-animation {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation: carBounce 1s ease-in-out infinite;
}

.car-body {
  width: 120rpx;
  height: 60rpx;
  position: relative;
}

.car-top {
  width: 80rpx;
  height: 30rpx;
  background-color: #1aad19;
  border-radius: 20rpx 20rpx 0 0;
  position: absolute;
  top: 0;
  left: 20rpx;
}

.car-bottom {
  width: 120rpx;
  height: 30rpx;
  background-color: #1aad19;
  border-radius: 10rpx;
  position: absolute;
  bottom: 0;
}

.wheel {
  width: 20rpx;
  height: 20rpx;
  background-color: #333;
  border-radius: 50%;
  position: absolute;
  bottom: -10rpx;
  animation: wheelRotate 1s linear infinite;
}

.wheel-left {
  left: 20rpx;
}

.wheel-right {
  right: 20rpx;
}

.waiting-info {
  margin-bottom: 20rpx;
  width: 100%;
  text-align: center;
}

.waiting-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.waiting-text {
  font-size: 28rpx;
  color: #666;
}

.primary-btn,
.secondary-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  font-size: 30rpx;
  font-weight: 500;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.primary-btn {
  background-color: #1aad19;
  color: #fff;
  transition: all 0.3s ease;
}

.primary-btn[disabled] {
  opacity: 0.6;
}

.primary-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.secondary-btn {
  background-color: #f0f0f0;
  color: #333;
}

.tips-section {
  margin-bottom: 30rpx;
  padding: 30rpx;
  background-color: #fff9f0;
  border-radius: 16rpx;
}

.tips-title {
  font-size: 28rpx;
  color: #ff9800;
  margin-bottom: 16rpx;
  display: block;
}

.tips-content {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 12rpx;
  display: block;
}

/* 添加安全底部边距 */
.safe-bottom {
  margin-bottom: 240rpx; /* 底部按钮区域高度 + 额外边距 */
}

/* 倒计时圆环动画 */
@keyframes countdown {
  from {
    transform: scale(1);
  }
  to {
    transform: scale(0);
  }
}

@keyframes moveRoad {
  from {
    background-position: 0 0;
  }
  to {
    background-position: -40rpx 0;
  }
}

@keyframes carBounce {
  0%, 100% {
    transform: translate(-50%, -50%);
  }
  50% {
    transform: translate(-50%, -55%);
  }
}

@keyframes wheelRotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 车主回复弹窗样式 */
.owner-reply-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.reply-content {
  width: 80%;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.reply-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1rpx solid #eee;
}

.reply-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  padding: 0 20rpx;
}

.reply-body {
  padding: 40rpx 30rpx;
}

.reply-message {
  font-size: 30rpx;
  color: #333;
  line-height: 1.5;
  display: block;
  margin-bottom: 20rpx;
}

.reply-time {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.reply-footer {
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #eee;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #1aad19;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}

/* 等待状态文本动画 */
.waiting-text {
  animation: fadeInOut 2s infinite;
}

@keyframes fadeInOut {
  0%, 100% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
}

/* 添加车主回复区域样式 */
.owner-response {
  margin-top: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  width: 100%;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  animation: slideUp 0.3s ease-out;
}

.response-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.response-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.response-time {
  font-size: 24rpx;
  color: #999;
}

.response-content {
  background-color: #f8f8f8;
  border-radius: 8rpx;
  padding: 16rpx;
}

.response-message {
  font-size: 28rpx;
  color: #333;
  line-height: 1.5;
}

@keyframes slideUp {
  from {
    transform: translateY(20rpx);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

/* 错误状态样式 */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 40rpx;
  background: #fff;
  border-radius: 16rpx;
  margin: 30rpx 0;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.error-icon {
  width: 200rpx;
  height: 200rpx;
  position: relative;
  margin-bottom: 40rpx;
}

.car-icon {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.car-body {
  width: 160rpx;
  height: 80rpx;
  position: relative;
  opacity: 0.5;
}

.car-top {
  width: 100rpx;
  height: 40rpx;
  background-color: #ff4d4f;
  border-radius: 20rpx 20rpx 0 0;
  position: absolute;
  top: 0;
  left: 30rpx;
}

.car-bottom {
  width: 160rpx;
  height: 40rpx;
  background-color: #ff4d4f;
  border-radius: 10rpx;
  position: absolute;
  bottom: 0;
}

.wheel {
  width: 24rpx;
  height: 24rpx;
  background-color: #333;
  border-radius: 50%;
  position: absolute;
  bottom: -12rpx;

  &:first-child {
    left: 30rpx;
  }

  &:last-child {
    right: 30rpx;
  }
}

.error-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 80rpx;
  height: 80rpx;
  background: #ff4d4f;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-size: 48rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 12rpx rgba(255, 77, 79, 0.3);
  animation: pulse 2s infinite;
}

.error-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 16rpx;
  text-align: center;
}

.error-desc {
  font-size: 28rpx;
  color: #666;
  text-align: center;
  line-height: 1.5;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

/* 修改消息记录区域样式 */
.message-log-section {
  margin-top: 30rpx;
  width: 100%;
}

.message-log-list {
  height: 300rpx;
}

.message-log-item {
  margin-bottom: 20rpx;
  padding: 16rpx;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8rpx;

  &.system-message {
    background-color: rgba(240, 240, 240, 0.9);

    .message-content {
      color: #666;
    }
  }
}

.message-time {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.message-content {
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
}
</style>